<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        #messageArea {
            height: 300px;
            border: 1px solid #ccc;
            overflow-y: auto;
            margin-bottom: 10px;
            padding: 10px;
        }
        #messageForm {
            display: flex;
        }
        #messageInput {
            flex-grow: 1;
            padding: 8px;
            margin-right: 10px;
        }
        .message {
            margin-bottom: 5px;
            padding: 5px;
            border-radius: 5px;
        }
        .self {
            background-color: #e3f2fd;
            text-align: right;
        }
        .other {
            background-color: #f5f5f5;
        }
        .system {
            color: #757575;
            font-style: italic;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>WebSocket聊天室</h1>
    <div id="messageArea"></div>
    <form id="messageForm">
        <input type="text" id="messageInput" placeholder="输入消息..." required>
        <button type="submit">发送</button>
    </form>
    <div id="status">连接中...</div>

    <script>
        // 修改为您的服务器地址和端口
        const socket = new WebSocket('ws://localhost:8081');
        
        const messageArea = document.getElementById('messageArea');
        const messageForm = document.getElementById('messageForm');
        const messageInput = document.getElementById('messageInput');
        const statusDisplay = document.getElementById('status');
        
        let myUserId = null;
        let reconnectAttempts = 0;
        const maxReconnectAttempts = 5;
        let lastPingTime = Date.now();
        
        // 处理连接打开
        socket.onopen = function(e) {
            statusDisplay.textContent = '已连接';
            addMessage('系统', '已连接到聊天服务器', 'system');
            reconnectAttempts = 0; // 重置重连次数
            lastPingTime = Date.now();
        };
        
        // 处理接收消息
        socket.onmessage = function(event) {
            const data = JSON.parse(event.data);
            
            if (data.type === 'register') {
                myUserId = data.userId;
                addMessage('系统', `您已加入聊天，您的ID是: ${myUserId}`, 'system');
            } 
            else if (data.type === 'message') {
                const isSelf = data.fromUserId === myUserId;
                addMessage(
                    isSelf ? '我' : data.fromUserId, 
                    data.message, 
                    isSelf ? 'self' : 'other',
                    data.timestamp
                );
            }
            else if (data.type === 'history') {
                // 处理历史消息
                messageArea.innerHTML = ''; // 清空消息区域
                data.messages.forEach(msg => {
                    const isSelf = msg.fromUserId === myUserId;
                    addMessage(
                        isSelf ? '我' : msg.fromUserId, 
                        msg.message, 
                        isSelf ? 'self' : 'other',
                        msg.timestamp
                    );
                });
                addMessage('系统', '已加载聊天历史', 'system');
            }
            else if (data.type === 'ping') {
                // 响应服务器的心跳
                lastPingTime = Date.now();
                socket.send(JSON.stringify({ type: 'pong' }));
            }
        };
        
        // 处理连接关闭
        socket.onclose = function(event) {
            if (event.wasClean) {
                statusDisplay.textContent = `连接已关闭，代码=${event.code} 原因=${event.reason}`;
            } else {
                statusDisplay.textContent = '连接断开';
            }
            addMessage('系统', '与服务器的连接已断开', 'system');
            
            // 尝试重连
            if (reconnectAttempts < maxReconnectAttempts) {
                reconnectAttempts++;
                const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
                addMessage('系统', `将在 ${delay/1000} 秒后尝试重新连接...`, 'system');
                setTimeout(() => {
                    location.reload();
                }, delay);
            } else {
                addMessage('系统', '重连次数过多，请手动刷新页面', 'system');
            }
        };
        
        // 处理连接错误
        socket.onerror = function(error) {
            statusDisplay.textContent = `连接错误`;
            addMessage('系统', '连接错误，请刷新页面重试', 'system');
            console.error('WebSocket Error:', error);
        };
        
        // 发送消息
        messageForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const message = messageInput.value.trim();
            if (message && socket.readyState === WebSocket.OPEN) {
                socket.send(JSON.stringify({
                    type: 'message',
                    message: message
                }));
                messageInput.value = '';
            }
        });
        
        // 添加消息到聊天区域
        function addMessage(sender, message, type, timestamp = '') {
            const messageElement = document.createElement('div');
            messageElement.classList.add('message', type);
            
            const time = timestamp || new Date().toLocaleTimeString();
            messageElement.innerHTML = `<strong>${sender}</strong> ${time ? `[${time}]` : ''}: ${message}`;
            
            messageArea.appendChild(messageElement);
            messageArea.scrollTop = messageArea.scrollHeight;
        }
    </script>
</body>
</html> 